<template>
  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-radio-group v-model="checkAll" @change="checkAllClick">
        <el-radio :label="true" border style="margin-right: 12px;">全选</el-radio>
        <el-radio :label="false" border>取消全选</el-radio>
      </el-radio-group>
    </el-col>
    <el-col :span="1.5">
      <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
    </el-col>
    <el-col :span="1.5" :style="{ padding: activeTab != '1' ? '0' : '0 5px' }">
      <el-button type="primary" icon="Setting" @click="handleQuality" v-show="activeTab == '1'">系统质检</el-button>
    </el-col>
    <el-col :span="1.5" :style="{ padding: activeTab != '2' ? '0' : '0 5px' }">
      <el-button type="primary" icon="Setting" @click="submitQuality" v-show="activeTab == '2'">提交质检</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="primary" icon="Tickets" @click="qualityDetail">项目质检情况</el-button>
    </el-col>
  </el-row>
  <el-scrollbar style="height: calc(100% - 40px - 56px)" ref="scrollbarRef">
    <div v-for="(item, index) in data" :key="item.label" class="select">
      <span class="select-row select-first"
        v-if="activeTab == '1' || item.children?.reduce((prev, cur) => { return prev + cur.tableData?.length }, 0)">
        <el-icon @click="caretChange(item)">
          <CaretRight v-show="item.caret == 0" />
          <CaretBottom v-show="item.caret == 1" />
        </el-icon>
        <el-checkbox v-model="item.checked" @change="changeChecked(item)" />
        <span @click="caretChange(item)">{{ item.label }}</span>
      </span>
      <el-collapse-transition>
        <div v-if="item.children?.length > 0 && item.caret == 1">
          <div v-for="itemChild in item.children" :key="itemChild.pathName" class="select-child">
            <div v-if="activeTab == '1' || itemChild.tableData?.length > 0">
              <span class="select-row">
                <el-icon @click="caretChange(itemChild)">
                  <CaretBottom v-if="itemChild.caret == 1" />
                  <CaretRight v-else="itemChild.caret == 0" />
                </el-icon>
                <el-checkbox v-model="itemChild.checked" @change="changeChecked(itemChild)" />
                <span @click="caretChange(itemChild)">{{ itemChild.label }}</span>
              </span>
              <el-collapse-transition>
                <div v-show="itemChild.caret == 1">
                  <el-table v-loading="item.tableLoading" :data="itemChild.tableData" :border="true" stripe
                    @selection-change="selection => tableChange(selection, itemChild)"
                    :ref="`tableRef-${itemChild.pathName}-${activeTab}`">
                    <el-table-column type="selection" width="55" align="center" v-if="activeTab == '2'" />
                    <el-table-column label="编号" prop="id" align="center">
                      <template #default="{ row }">
                        <el-link :underline="false" type="primary"
                          @click="goToDetail(row, itemChild.pathName, itemChild.idName, itemChild.label)"
                          v-if="activeTab != '2'">
                          {{ row.id }}
                        </el-link>
                        <span v-else>{{ row.id }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="省" prop="province" align="center" />
                    <el-table-column label="市" prop="city" align="center" />
                    <el-table-column label="区（县）" prop="county" align="center" />
                    <el-table-column label="质检时间" prop="qcTime" align="center" v-if="activeTab != '1'" />
                    <el-table-column label="系统质检流程" prop="" align="center">
                      <template #default="{ row }">
                        <el-button type="text" @click="viewQuality(row)">查看</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" v-if="activeTab == 2">
                      <template #default="{ row }">
                        <el-button type="text"
                          @click="goToDetail(row, itemChild.pathName, itemChild.idName, itemChild.label)">查看表单</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <pagination style="margin-top: 15px" v-show="itemChild.total > rows" :total="itemChild.total"
                    v-model:page="page" v-model:limit="rows" @pagination="queryList(itemChild, index)" />
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>
      </el-collapse-transition>
    </div>
  </el-scrollbar>
  <Quality v-model:open="qualityOpen" :data="qualityData" />
  <QualityResult v-model:open="qualityDetailOpen" :data="qualityDetailData" />
</template>
<script setup>
import { treeDataSmall } from '@/views/businessManage/common/intergrateTree'
import { getAll } from '@/api/businessManage/dataLoader/otherData'
import { getResult, qualityControl } from '@/api/businessManage/dataIntegrate'
import Quality from '@/views/businessManage/common/quality'
import QualityResult from '@/views/businessManage/dataIntegrate/qualityResult'
import { submit } from '@/api/businessManage/dataLoader/otherData'

const props = defineProps({
  activeTab: String,
  id: String,
  isPmId: Boolean,
  pmId: String,
  treeData: Array,
})
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const initData = () => {
  return treeDataSmall
}
let data = ref(initData())

const pathName = ref('')
const page = ref(1)
const rows = ref(10)
const checkAll = ref()

// 展开收起
const caretChange = (item) => {
  item.caret = item.caret == 0 ? 1 : 0
  nextTick(() => {
    if(item.children?.length > 0){
      item.children.map(itemChild => {
        if (proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`]) {
          if (itemChild.caret == 1 && itemChild.checked) {
            proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.clearSelection()
            proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.toggleAllSelection()
          }
          if (itemChild.caret == 1 && !itemChild.checked) {
            proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.clearSelection()
          }
        }
      })
    }
    if (proxy.$refs[`tableRef-${item.pathName}-${props.activeTab}`]) {
      // if (item.caret == 1 && item.checked && item.tableData?.length > 0) {
      if (item.caret == 1 && item.checked) {
        proxy.$refs[`tableRef-${item.pathName}-${props.activeTab}`][0]?.clearSelection()
        proxy.$refs[`tableRef-${item.pathName}-${props.activeTab}`][0]?.toggleAllSelection()
      }
      if (item.caret == 1 && !item.checked) {
        proxy.$refs[`tableRef-${item.pathName}-${props.activeTab}`][0]?.clearSelection()
      }
    }
  })
}
// 多选框
const changeChecked = item => {
  if (item.children?.length > 0) {
    item.children.map(itemChild => {
      itemChild.checked = item.checked
      if (proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`] && itemChild.caret == '1') {
        if (itemChild.checked) {
          proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.clearSelection()
          proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.toggleAllSelection()
        } else {
          proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.clearSelection()
        }
      }
    })
  } else {
    if (proxy.$refs[`tableRef-${item.pathName}-${props.activeTab}`] && item.caret == '1') {
      proxy.$refs[`tableRef-${item.pathName}-${props.activeTab}`][0]?.toggleAllSelection()
    }
  }
}
const ids = ref({})
// 表格选择
const tableChange = (selection, item) => {
  if (props.activeTab == '2') {
    item.checked = selection.length > 0
  }
}
let secondFlag = ref([])
watch(() => secondFlag.value, () => {
  if (secondFlag.value.length == secondNum.value) {
    if (props.activeTab == '1') {
      data.value[0].caret = 1
      data.value[0].children.map(item => item.caret = 1)
    } else {
      let itemChildIndex = secondFlag.value.filter(item => item != null).sort((a, b) => a - b)[0]
      if (itemChildIndex >= 0) {
        data.value[itemChildIndex].caret = 1
        data.value[itemChildIndex]?.children.map(cur => {
          cur.caret = 1
          nextTick(() => {
            if (props.activeTab == '2' && proxy.$refs[`tableRef-${cur.pathName}-${props.activeTab}`] && cur.caret == 1) {
              if(cur.checked){
                proxy.$refs[`tableRef-${cur.pathName}-${props.activeTab}`][0]?.clearSelection()
                proxy.$refs[`tableRef-${cur.pathName}-${props.activeTab}`][0]?.toggleAllSelection()
              }else{
                proxy.$refs[`tableRef-${cur.pathName}-${props.activeTab}`][0]?.clearSelection()
              }
            }
          })
        })
      }
    }
  }
}, { deep: true })

const queryList = (item, index) => {
  let baseUrl = item.baseUrl
  item.tableLoading = true
  let params = { page: page.value, rows: rows.value, qcFlag: props.activeTab }
  props.isPmId ? params.pmId = props.id : params.smId = props.id
  if (!props.id) {
    item.tableLoading = false
    return
  }
  getAll(baseUrl, params).then(res => {
    item.tableData = res.data.rows
    item.total = res.data.total || 0
    item.tableLoading = false
    secondFlag.value.push(item.tableData?.length > 0 ? index : null)
  })
}

// 全选/取消全选
const checkAllClick = val => {
  data.value.map(item => {
    item.checked = val
    item.children.map(itemChild => {
      itemChild.checked = val
      nextTick(() => {
        if (props.activeTab == '2' && proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`] && itemChild.caret == '1') {
          if (val) {
            proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.clearSelection()
            proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.toggleAllSelection()
          } else {
            proxy.$refs[`tableRef-${itemChild.pathName}-${props.activeTab}`][0]?.clearSelection()
          }
        }
      })
    })
    return item
  })
}

// 判断左侧栏数据返回
const isData=()=>{
  if(props.treeData.length==0){
    proxy.$modal.msgWarning('没有项目数据!!!')
    return false
  }else{
    return true
  }
}

// 导出
const handleExport = () => {
  let flag = isData()
  if (!flag) return
  let checkedData = []
  data.value.map(item => {
    item.children?.map(itemChild => {
      itemChild.checked && checkedData.push(itemChild.qualityPath.slice(4))
    })
  })
  if (checkedData.length == 0) {
    proxy.$modal.msgWarning('请至少选择一个分类！')
    return
  }

  let excelName
  switch (props.activeTab) {
    case '1':
      excelName = `数据检测集成-待质检`
      break
    case '2':
      excelName = `数据检测集成-质检未通过`
      break
    case '3':
      excelName = `数据检测集成-质检通过`
      break
  }
  let params = { qcFlag: props.activeTab, mark: checkedData.join(',') }
  props.isPmId ? params.pmId = props.id : params.smId = props.id
  proxy.download(`/qc/result/downLoadZip`, params, `${excelName}${new Date().getTime()}.zip`)
  // proxy.download(`/qc/result/downLoadZip`, params)
}
// 系统质检
const handleQuality = () => {
  let flag = isData()
  if (!flag) return
  let qualityPathData = []
  data.value.map(item => {
    item.children?.map(itemChild => {
      itemChild.checked && qualityPathData.push(itemChild.qualityPath)
    })
  })
  if (qualityPathData.length == 0) {
    proxy.$modal.msgWarning('请至少选择一个分类进行系统质检！')
    return
  }
  let params = { qcFlag: props.activeTab }
  props.isPmId ? params.pmId = route.query.id : params.smId = route.query.id
  let all = []
  qualityPathData.map(item => {
    all.push(qualityControl(item, params))
  })
  Promise.all(all).then(() => {
    proxy.$modal.msgSuccess('系统质检成功！')
    refreshTable()
  }).catch(() => { })
}
// 提交质检
const submitQuality = () => {
  let checkedData = []
  data.value.map(item => {
    item.children?.map(itemChild => {
      ids.value[itemChild.pathName] = itemChild.tableData?.map(cur => cur[itemChild.idName])
      if (itemChild.checked && itemChild.tableData.length > 0) {
        checkedData.push(itemChild)
      }
    })
  })
  if (checkedData.length == 0) {
    proxy.$modal.msgWarning(`请至少选择一个分类进行提交质检！`)
    return
  }
  let all = []
  let isHasData = false
  checkedData.map(item => {
    if (!ids.value[item.pathName] && !isHasData) {
      isHasData = true
      proxy.$modal.msgWarning(`请至少选择一条【${item.label}】数据！`)
    }
    all.push(submit(item.baseUrl, ids.value[item.pathName]))
  })
  if (!isHasData) {
    Promise.all(all).then(() => {
      proxy.$modal.msgSuccess('提交质检成功！')
      refreshTable()
    }).catch(() => { })
  }
}
// 系统质检流程-查看
const qualityOpen = ref(false)
const qualityData = ref({})
const viewQuality = (row) => {
  qualityOpen.value = true
  qualityData.value = row
}
// 项目质检情况
const qualityDetailOpen = ref(false)
const qualityDetailData = ref({})
const qualityDetail = () => {
  let flag = isData()
  if (!flag) return
  qualityDetailOpen.value = true
  getResult({ pmId: props.pmId }).then(res => {
    qualityDetailData.value = res.data
  })
}
const goToDetail = (row, pathName, idName, label) => {
  router.push({ path: `/businessManage/dataIntegrate/main/${pathName}`, query: { id: route.query.id, detailId: row[idName], typeName: label } })
}

// 刷新当前展开的表格
const refreshTable = () => {
  data.value.map((item, index) => {
    item.caret = 0
    item.children.map(itemChild => {
      itemChild.caret = 0
      queryList(itemChild, index)
    })
  })
}
let secondNum = ref(0)
watch([() => props.activeTab, () => props.id], () => {
  secondFlag.value = []
  proxy.$refs.scrollbarRef.setScrollTop(0)
  secondNum.value = 0
  data.value.map((item, index) => {
    item.caret = 0
    item.children?.map(itemChild => {
      secondNum.value++
      itemChild.caret = 0
      queryList(itemChild, index)
    })
  })
})
</script>
<style scoped lang="scss">
.select {
  &-row {
    line-height: 2;
    font-size: var(--el-font-size-base);
    color: #606266;

    &:hover {
      cursor: pointer;
    }

    &>.el-icon,
    &>.el-checkbox,
    &>span {
      vertical-align: middle;
    }

    &>.el-checkbox {
      padding: 0 3px;
    }
  }

  &-first {
    font-weight: bold;
  }

  &-child {
    padding-left: 20px;
  }
}
</style>